﻿using NetEasyMusic.Lib.Models;
using Newtonsoft.Json.Linq;

namespace NetEasyMusic.Lib.Data;

public abstract class DataBasic : IDisposable
{
    //
    //neteasecloudmusicapi.vercel.app

    private const string Url = "https://neteasy.zeabur.app";

    protected DataBasic(string cookie)
    {
        SharedClient = new HttpClient()
            { BaseAddress = new Uri(Url) };
        Cookie = cookie;
    }

    protected DataBasic()
    {
        SharedClient = new HttpClient
            { BaseAddress = new Uri(Url) };
        Cookie = "";
    }

    protected DataBasic(string url, bool isUse = false)
    {
        SharedClient = new HttpClient { BaseAddress = new Uri(url) };
        Cookie = "";
    }

    protected HttpClient SharedClient { get; }
    protected string Cookie { get; }


    protected async Task<JObject?> GetFormString(string url)
    {
        try
        {
            return JObject.Parse(await SharedClient.GetStringAsync(url));
        }
        catch (Exception e)
        {
#if DEBUG
            Console.WriteLine(e.Message);
#endif
            return null;
        }
    }

    public void Dispose()
    {
        SharedClient.Dispose();
        GC.SuppressFinalize(this);
    }

    /// <summary>
    /// 获取包含歌曲封面的热门歌曲
    /// </summary>
    /// <param name="id">歌曲ID 集合</param>
    /// <returns>包含歌曲封面的热门歌曲</returns>
    public async Task<SongModel[]> GetTopSongsAndPic(string id)
    {
        var obj = await GetFormString($"/song/detail?ids={id}");
        return obj?["songs"]?.Select(x => new SongModel()
        {
            Name = x["name"]?.ToObject<string>()!,
            Id = x["id"]?.ToObject<string>()!,
            PicUrl = x["al"]?["picUrl"]?.ToObject<string>()!,
            Time = x["dt"]!.ToObject<string>()!,
            Artists = x["ar"]?.Select(y => new ArtistModel(y)).ToArray() ?? [],
            Album = x["al"]?["name"]?.ToObject<string>()!,
            AlbumId = x["al"]?["id"]?.ToObject<string>()!
        }).ToArray() ?? [];
    }
}